const { createServer } = require('http');
const { join } = require('path');
const { readFile } = require('fs');

const server = createServer();

server.on('request', (req, res) => {
  const { url } = req;

  let fpath = '';

  if (url === '/') {
    fpath = join(__dirname, './clock/index.html');
  } else {
    // url:  /index.js    /index.css
    // url:  /clock/index.html
    if (url.startsWith('/clock/')) {
      fpath = join(__dirname, url);
    } else {
      fpath = join(__dirname, './clock', url);
    }
  }

  readFile(fpath, 'UTF-8', (err, data) => {
    if (err) return res.end('404 Not found!');
    res.end(data);
  });

  
});

server.listen(80, () => {
  console.log('server started at http://localhost');
});
